package com.hsck.order.kds.setup.fragment

import android.app.AlertDialog
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.hsck.order.kds.R
import com.hsck.order.kds.base.bean.CategoryBean
import com.hsck.order.kds.base.bean.FoodNumBean
import com.hsck.order.kds.base.common.shortToast
import com.hsck.order.kds.base.utils.ListUtils
import com.hsck.order.kds.base.utils.LogUtil
import com.hsck.order.kds.base.utils.setOnSingleClickListener
import com.hsck.order.kds.base.isnoam.view.BaseFragment
import com.hsck.order.kds.databinding.FragmentFoodBinding
import com.hsck.order.kds.setup.ClearingSettingsActivity
import com.hsck.order.kds.setup.adapter.FoodAdapter
import com.hsck.order.kds.setup.adapter.FoodClassifAdapter
import com.hsck.order.kds.setup.adapter.FoodNumAdapter
import com.hsck.order.kds.setup.adapter.KeyboardAdapter
import kotlinx.android.synthetic.main.dialog_donot_sell.view.*
import kotlinx.android.synthetic.main.dialog_guqing.view.*
import kotlinx.android.synthetic.main.dialog_tishi.view.*


class FoodFragment : BaseFragment<FragmentFoodBinding>() {

    var page = 1
    val list = arrayListOf<CategoryBean>()
    val listFood = arrayListOf<CategoryBean>()
    var newListFood = arrayListOf<List<CategoryBean>>()
    var numList = arrayListOf<FoodNumBean>()
    lateinit var context: ClearingSettingsActivity

    private val adapterClassif by lazy { FoodClassifAdapter(R.layout.item_food_classif) }
    private val adapterFood by lazy { FoodAdapter(R.layout.item_food) }
    private val adapterFoodNum by lazy { FoodNumAdapter(R.layout.item_food_num) }


    override fun inflateBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentFoodBinding {
        return FragmentFoodBinding.inflate(inflater)
    }

    override fun loadDataOnce() {
        super.loadDataOnce()
        context = requireActivity() as ClearingSettingsActivity
        setRVClassif()
        setRVFood()

        adapterFood.onItemLongClick = {
            setGqSetDialog()
        }
    }

    /**
     * 分类设置
     */
    private fun setRVClassif() {
        binding.apply {
            rvFoodClssif.layoutManager =
                LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
            rvFoodClssif.adapter = adapterClassif

            for (i in 1..12) {
                list.add(CategoryBean("$i"))
            }
            list.first().isSelected = true
            adapterClassif.datas = list
            setRvPosition()

            //上一页分类
            relFoodClssifPreviousPage.setOnClickListener {
                try {
                    var selectIndex = 0
                    for ((index, value) in list.withIndex()) {
                        if (value.isSelected) {
                            selectIndex = index
                        }
                    }
                    if (selectIndex - 1 >= 0) {
                        list.forEach {
                            it.isSelected = false
                        }
                        list[selectIndex - 1].isSelected = true
                        val layoutManager = rvFoodClssif.layoutManager as LinearLayoutManager
                        layoutManager.scrollToPositionWithOffset(selectIndex - 1, 0)
                        adapterClassif.notifyDataSetChanged()
                        setRvPosition()

                        //重新设置page 为1
                        page = 1
                        numList.forEach {
                            it.isSelected = false
                        }
                        numList[page - 1].isSelected = true
                        adapterFoodNum.notifyDataSetChanged()
                    }
                } catch (e: Exception) {
                    LogUtil.e("${e.message}")
                }
            }
            //下一页分类
            relFoodClssifNextPage.setOnClickListener {
                try {
                    var selectIndex = 0
                    for ((index, value) in list.withIndex()) {
                        if (value.isSelected) {
                            selectIndex = index
                        }
                    }
                    if (selectIndex + 1 <= list.size - 1) {
                        list.forEach {
                            it.isSelected = false
                        }
                        list[selectIndex + 1].isSelected = true
                        val layoutManager = rvFoodClssif.layoutManager as LinearLayoutManager
                        layoutManager.scrollToPositionWithOffset(selectIndex + 1, 0)
                        adapterClassif.notifyDataSetChanged()
                        setRvPosition()

                        //重新设置page 为1
                        page = 1
                        numList.forEach {
                            it.isSelected = false
                        }
                        numList[page - 1].isSelected = true
                        adapterFoodNum.notifyDataSetChanged()
                    }
                } catch (e: Exception) {
                    LogUtil.e("${e.message}")
                }


            }

            if (list.size > 10) {
                linFoodClssif.visibility = View.VISIBLE
            } else {
                linFoodClssif.visibility = View.GONE
            }
            adapterClassif.onPositionClick = { it, po ->
                list.forEach {
                    it.isSelected = false
                }
                list[po].isSelected = true
                adapterClassif.notifyDataSetChanged()
                setRvPosition()

                //重新设置page 为1
                page = 1
                numList.forEach {
                    it.isSelected = false
                }
                numList[page - 1].isSelected = true
                adapterFoodNum.notifyDataSetChanged()
            }
        }
    }

    /**
     * 菜品设置
     */
    private fun setRVFood() {
        binding.apply {
            rvFood.layoutManager = GridLayoutManager(context, 6)
            rvFood.adapter = adapterFood

            for (i in 1..241) {
                listFood.add(CategoryBean("$i"))
            }
            if (listFood.size > 0) {
                linFoodNum.visibility = View.VISIBLE
                newListFood = ListUtils.splitList(listFood, 24) as ArrayList<List<CategoryBean>>
                adapterFood.datas = newListFood.first()
                rvFoodNum.layoutManager =
                    LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
                rvFoodNum.adapter = adapterFoodNum

                for (index in newListFood.indices) {
                    numList.add(FoodNumBean(index + 1))
                }
                numList.first().isSelected = true
                adapterFoodNum.datas = numList

            } else {
                linFoodNum.visibility = View.GONE
            }

            adapterFoodNum.onItemClick = {
                numList.forEach {
                    it.isSelected = false
                }
                it.isSelected = true
                page = it.index
                adapterFood.datas = newListFood[page - 1]
                adapterFoodNum.notifyDataSetChanged()
            }

            tvPreviousPagev.setOnClickListener {
                try {
                    if (page - 1 > 0) {
                        numList.forEach {
                            it.isSelected = false
                        }
                        page -= 1
                        numList[page - 1].isSelected = true
                        adapterFoodNum.notifyDataSetChanged()
                        adapterFood.datas = newListFood[page - 1]
                    }
                } catch (e: Exception) {
                    LogUtil.e("${e.message}")
                }
            }
            tvNextPage.setOnClickListener {
                try {
                    if (page + 1 <= numList.size) {
                        numList.forEach {
                            it.isSelected = false
                        }
                        page += 1
                        numList[page - 1].isSelected = true
                        adapterFoodNum.notifyDataSetChanged()
                        adapterFood.datas = newListFood[page - 1]
                    }
                } catch (e: Exception) {
                    LogUtil.e("${e.message}")
                }

            }


        }
    }

    private fun setRvPosition() {
        var selectIndex = 0
        for ((index, value) in list.withIndex()) {
            if (value.isSelected) {
                selectIndex = index
            }
        }
        if (selectIndex == 0) {
            binding.imgFoodClssifPreviousPage.setImageResource(R.drawable.arrow_left_grey_icon)
            binding.imgFoodClssifNextPage.setImageResource(R.drawable.arrow_right_black_icon)
        } else if (selectIndex >= list.size - 1) {
            binding.imgFoodClssifPreviousPage.setImageResource(R.drawable.arrow_left_black_icon)
            binding.imgFoodClssifNextPage.setImageResource(R.drawable.arrow_right_grey_icon)
        } else {
            binding.imgFoodClssifPreviousPage.setImageResource(R.drawable.arrow_left_black_icon)
            binding.imgFoodClssifNextPage.setImageResource(R.drawable.arrow_right_black_icon)
        }
    }

    private val adapterPhone by lazy { KeyboardAdapter(R.layout.item_keyboard) }

    /**
     * 沽清设置
     */
    private fun setGqSetDialog() {
        //R.style.***一定要写，不然不能充满整个屏宽，引用R.style.AppTheme就可以tm
        val createDialog = AlertDialog.Builder(requireActivity(), R.style.Dialog_FullScreen).create()
        // 设置Dialog的Window的软键盘模式为隐藏
        createDialog.getWindow()!!
            .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        val view = View.inflate(requireActivity(), R.layout.dialog_guqing, null)
        val window = createDialog.getWindow()

//        window.setGravity(Gravity.BOTTOM or Gravity.RIGHT)
        //设置dialog弹出后会点击屏幕或物理返回键，dialog不消失
        createDialog.setCanceledOnTouchOutside(false)
        createDialog.setCancelable(false)
        createDialog.show()
        window!!.setContentView(view)
        window.setBackgroundDrawableResource(R.drawable.shape_grayf5_borderless20)
        //获得window窗口的属性
        val params = window.getAttributes()
        //设置窗口宽度为充满全屏
        val width = resources.getDimension(R.dimen.dp_1476).toInt()
        val height = resources.getDimension(R.dimen.dp_790).toInt()
        params.width = width
        params.height = height
//        params.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE//显示dialog的时候,就显示软键盘
        params.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND//就是这个属性导致window后所有的东西都成暗淡
        params.dimAmount = 0.5f//设置对话框的透明程度背景(非布局的透明度)
        //将设置好的属性set回去
        window.setAttributes(params)

        view.img_dialog_guqing_close.setOnSingleClickListener {
            createDialog.dismiss()
        }


        view.rv_dialog_guqing.layoutManager = GridLayoutManager(requireActivity(), 3)
        view.rv_dialog_guqing.adapter = adapterPhone

        val list = arrayListOf<String>()
        for (i in 1..12) {
            if (i < 10) {
                list.add(i.toString())
            } else if (i == 10) {
                list.add("清空")
            } else if (i == 11) {
                list.add("0")
            } else if (i == 12) {
                list.add("删除")
            }
        }
        adapterPhone.datas = list

        adapterPhone.onItemClick = {
            when (it) {
                "清空" -> {
                    view.edt_dialog_gqset_dailySaleNumLimit.text = ""
                }
                "删除" -> {
                    val num = view.edt_dialog_gqset_dailySaleNumLimit.text.toString().trim()
                    if (num != "") {
                        view.edt_dialog_gqset_dailySaleNumLimit.text =
                            num.substring(0, num.length - 1)
                    }
                }
                "0" -> {
                    if (view.edt_dialog_gqset_dailySaleNumLimit.text.toString().trim() != "") {
                        val num = view.edt_dialog_gqset_dailySaleNumLimit.text.toString().trim()
                        view.edt_dialog_gqset_dailySaleNumLimit.text = "$num$it"
                    }
                }
                else -> {

                    val num = view.edt_dialog_gqset_dailySaleNumLimit.text.toString().trim()
                    view.edt_dialog_gqset_dailySaleNumLimit.text = "$num$it"
                }
            }
        }


        view.img_dialog_gqset_kszsl.setOnSingleClickListener {
            if (view.img_dialog_gqset_kszslTs.visibility == View.VISIBLE) {
                view.img_dialog_gqset_kszslTs.visibility = View.GONE
            } else {
                view.img_dialog_gqset_kszslTs.visibility = View.VISIBLE
            }
        }
        view.img_dialog_gqset_mrxgsl.setOnSingleClickListener {
            if (view.img_dialog_gqset_mrxgslTs.visibility == View.VISIBLE) {
                view.img_dialog_gqset_mrxgslTs.visibility = View.GONE
            } else {
                view.img_dialog_gqset_mrxgslTs.visibility = View.VISIBLE
            }
        }

        view.btn_dialog_gqset_todaySellOutFlag.setOnSingleClickListener {
            setDonotSellDialog(createDialog)
            //今日售罄标识 Y/N
        }

        view.btn_dialog_gqset_qdgqset.setOnSingleClickListener {
            val num = view.edt_dialog_gqset_dailySaleNumLimit.text.toString().trim()
            if (!num.isNullOrEmpty()) {

                createDialog.dismiss()
            } else {
                requireActivity()?.shortToast("请输入每日限售数量")
            }
        }

    }


    /**
     * 沽清设置
     */
    private fun setDonotSellDialog(topDialog: AlertDialog) {
        //R.style.***一定要写，不然不能充满整个屏宽，引用R.style.AppTheme就可以tm
        val createDialog = AlertDialog.Builder(requireActivity(), R.style.Dialog_FullScreen).create()
        // 设置Dialog的Window的软键盘模式为隐藏
        createDialog.getWindow()!!
            .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        val view = View.inflate(requireActivity(), R.layout.dialog_donot_sell, null)
        val window = createDialog.getWindow()

//        window.setGravity(Gravity.BOTTOM or Gravity.RIGHT)
        //设置dialog弹出后会点击屏幕或物理返回键，dialog不消失
        createDialog.setCanceledOnTouchOutside(false)
        createDialog.setCancelable(false)
        createDialog.show()
        window!!.setContentView(view)
        window.setBackgroundDrawableResource(R.drawable.shape_white_borderless15)
        //获得window窗口的属性
        val params = window.getAttributes()
        //设置窗口宽度为充满全屏
        val width = resources.getDimension(R.dimen.dp_800).toInt()
        params.width = width
        params.height = WindowManager.LayoutParams.WRAP_CONTENT
//        params.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE//显示dialog的时候,就显示软键盘
        params.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND//就是这个属性导致window后所有的东西都成暗淡
        params.dimAmount = 0.5f//设置对话框的透明程度背景(非布局的透明度)
        //将设置好的属性set回去
        window.setAttributes(params)

        view.btn_dialog_donot_sell_qx.setOnSingleClickListener {
            topDialog.dismiss()
            createDialog.dismiss()
        }
        view.btn_dialog_donot_sell_qd.setOnSingleClickListener {
            topDialog.dismiss()
            createDialog.dismiss()
        }

    }

    /**
     * 取消沽清
     */
    private fun setQkDialog(data: String) {
        //R.style.***一定要写，不然不能充满整个屏宽，引用R.style.AppTheme就可以tm
        val createDialog = AlertDialog.Builder(requireActivity(), R.style.Dialog_FullScreen).create()
        // 设置Dialog的Window的软键盘模式为隐藏
        createDialog.getWindow()!!
            .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        val view = View.inflate(requireActivity(), R.layout.dialog_tishi, null)
        val window = createDialog.getWindow()

//        window.setGravity(Gravity.BOTTOM or Gravity.RIGHT)
        //设置dialog弹出后会点击屏幕或物理返回键，dialog不消失
        createDialog.setCanceledOnTouchOutside(false)
        createDialog.setCancelable(false)
        createDialog.show()
        window!!.setContentView(view)
        window.setBackgroundDrawableResource(R.drawable.shape_grayf5_borderless20)
        //获得window窗口的属性
        val params = window.getAttributes()
        //设置窗口宽度为充满全屏
        val width = WindowManager.LayoutParams.WRAP_CONTENT
        val height = WindowManager.LayoutParams.WRAP_CONTENT
        params.width = width
        params.height = height
//        params.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE//显示dialog的时候,就显示软键盘
        params.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND//就是这个属性导致window后所有的东西都成暗淡
        params.dimAmount = 0.5f//设置对话框的透明程度背景(非布局的透明度)
        //将设置好的属性set回去
        window.setAttributes(params)

        view.tv_dialog_tishi_title.text = "确认取消沽清"
        view.tv_dialog_tishi_msg.text = "取消沽清设置后，菜品可重新售卖"
        view.btn_dialog_tishi_qx.text = "取消"
        view.btn_dialog_tishi_qr.text = "确定"
        view.btn_dialog_tishi_qx.setOnClickListener {
            createDialog.dismiss()
        }
        view.btn_dialog_tishi_qr.setOnClickListener {
            createDialog.dismiss()
        }
    }

}